<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>首页-聚码网-站长交易平台</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
    <link rel="stylesheet" href="./public/static/index/bui/bui.css">
    <link rel="stylesheet" href="./public/static/index/css/two.css">
    <script src="./public/static/index/bui/zepto.js"></script>
    <script src="./public/static/index/bui/bui.js"></script>
    <link rel="icon" href="./public/favicon.ico">
    <!-- 聊天在线状态管理 -->
    <script src="./public/static/index/js/chat-status.js"></script>
    <!-- 添加图标字体支持 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <style>
        /* 图标字体样式 */
        .icon-home:before {
            content: "\f015";
            font-family: FontAwesome;
        }
        .icon-shoppingcart:before {
            content: "\f07a";
            font-family: FontAwesome;
        }
        .icon-edit:before {
            content: "\f044";
            font-family: FontAwesome;
        }
        .icon-search:before {
            content: "\f002";
            font-family: FontAwesome;
        }
        .icon-remove:before {
            content: "\f00d";
            font-family: FontAwesome;
        }
        .icon-list:before {
            content: "\f03a";
            font-family: FontAwesome;
        }
        /* 确保图标显示 */
        [class^="icon-"], [class*=" icon-"] {
            font-family: FontAwesome;
            font-style: normal;
            font-weight: normal;
            display: inline-block;
            text-decoration: inherit;
        }
        body {
            margin: 0;
            padding: 0;
            padding-bottom: 50px; /* 为底部导航留出空间 */
            background-color: #f3f5f8;
        }
        main {
            width: 100%;
            height: calc(100vh - 50px);
            overflow-y: auto;
            overflow-x: hidden;
            -webkit-overflow-scrolling: touch;
            background-color: #f3f5f8;
        }
        footer {
            background-color: #fff;
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            z-index: 1000;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
        }
        .bui-page {
            padding-bottom: 0;
            margin-bottom: 0;
        }
        .bui-list-pic .bui-pic img, .bui-list-photo .bui-thumbnail img {
            width: 100%;
            height: auto;
            aspect-ratio: 1;
            object-fit: cover;
        }
        /* 九宫格布局 - 每行3个商品 */
        .bui-list-pic.bui-fluid-space {
            margin: 0;
            padding: 8px 4px;
            overflow: hidden;
        }
        .bui-list-pic.bui-fluid-space::after {
            content: "";
            display: table;
            clear: both;
        }
        .bui-list-pic.bui-fluid-space .span4 {
            width: 33.333%;
            float: left;
            box-sizing: border-box;
            padding: 4px;
        }
        .bui-list-pic.bui-fluid-space .span4 .bui-pic {
            background-color: #fff;
            border-radius: 4px;
            overflow: hidden;
            margin-bottom: 0;
        }
        .bui-list-pic.bui-fluid-space .span4 .bui-pic-title {
            padding: 6px 8px;
            font-size: 0.26rem;
            color: #333;
            line-height: 1.4;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            min-height: 0.72rem;
        }
        .bui-list-pic.bui-fluid-space .span4 .bui-pic-img {
            width: 100%;
            background-color: #f5f5f5;
        }
        .bui-list-pic.bui-fluid-space .span4 .price-section {
            padding: 0 8px 8px 8px;
        }
        .bui-list-pic.bui-fluid-space .span4 .price-section .price {
            color: #fb0247;
            font-weight: bolder;
            font-size: 0.28rem;
        }
        .bui-nav>.active{
            color: #333;
        }
        .bui-nav>[class*=bui-btn].active:after {
            background: #333;
        }
        [class*=bui-btn] .bui-thumbnail{
            width: 1.2rem;
        }
        .bui-rating .bui-rating-cell{
            font-size: .2rem;
        }
        .bui-rating .bui-rating-cell-half, .bui-rating .bui-rating-cell-full{
            color: #ff0057;
        }
        .bui-nav>.active {
            color: #f9342a;
            background: #fff;
        }
        .top{
            position: absolute;
            top: 50px;
            left: 1px;
            z-index: 1;
            background-image: url(./public/static/index/images/top.png);
            background-repeat: no-repeat;
            background-position: center top;
            width: 100%;
            background-size: 100% 30px;
            height: 30px;
        }
        .bui-btn, [class^=bui-btn]{
            -webkit-user-select: none;
            -khtml-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
            background-color: #fff;
            cursor: pointer;
            text-align: center;
            padding-bottom: .25rem;
            padding-left: .2rem;
            padding-right: .3rem;
            line-height: 1.2;
            vertical-align: middle;
            -webkit-appearance: none;
            border: 1px solid #eee;
            margin: 0 auto;
            min-height: .6rem;
        }
        .round2 {
            border: 1px solid #ff9236;
            border-radius: 1px;
            font-size: 0.2rem;
            width: 70px;
            display:inline;
            margin-right: 1px;
        }
        .round3 {
            color: #ff9236;
            margin-left: 2.5px;
            margin-right: 2.5px;
        }
        .bui-thumbnail img {
            float: left;
            object-fit: cover;
        }
        .bui-nav{
            padding-bottom:2px;
        }
    </style>
</head>
<body>
    <div class="bui-page">
        <main>
            <div id="uiList" style="background-color: #f3f5f8;">
                <ul class="bui-list bui-list-pic bui-fluid-space" id="goodsList">
                    <!-- 商品将通过AJAX动态加载 -->
                </ul>
            </div>
        </main>
        
        <footer>
            <ul id="tabFootNav" class="bui-nav">
                <li id="homeGo" class="bui-btn bui-box-vertical">
                    <a href="./index.html" style="display: flex; flex-direction: column; align-items: center; text-decoration: none; color: inherit;">
                        <i class="icon-home"></i>
                        <div class="span1">首页</div>
                    </a>
                </li>
                <li id="classifyGo" class="bui-btn bui-box-vertical">
                    <a href="./clsssify.html" style="display: flex; flex-direction: column; align-items: center; text-decoration: none; color: inherit;">
                        <i class="icon-list"></i>
                        <div class="span1">分类</div>
                    </a>
                </li>
                <li id="shopCartGo" class="bui-btn bui-box-vertical">
                    <a href="./shopCart.html" style="display: flex; flex-direction: column; align-items: center; text-decoration: none; color: inherit;">
                        <i class="icon-shoppingcart"></i>
                        <div class="span1">购物车</div>
                    </a>
                </li>
                <li id="orderQueryGo" class="bui-btn bui-box-vertical">
                    <a href="./orderQuery.html" style="display: flex; flex-direction: column; align-items: center; text-decoration: none; color: inherit;">
                        <i class="icon-edit"></i>
                        <div class="span1">订单</div>
                    </a>
                </li>
            </ul>
        </footer>
    </div>

    <script>
        window.uiRating = bui.rating({
            id: "#rating",
            value: 5
        });

        var uiRating3 = bui.rating({
            id: "#rating3",
            disabled: true,
            value: 4
        });
    </script>
    <script>
        // 商品列表API地址
        var API_BASE_URL = "https://api.sc123.shop/";
        var GOODS_LIST_API = API_BASE_URL + "/api/v1/index/goods_list";
        
        // 设置聊天状态管理的API地址
        if (window.ChatStatus) {
            window.ChatStatus.setApiBaseUrl(API_BASE_URL);
        }

        // 渲染商品列表
        function renderGoods(goodsList) {
            var html = "";
            if (goodsList && goodsList.length > 0) {
                goodsList.forEach(function(item) {
                    // 处理图片URL：取第一个图片，如果是相对路径则拼接基础URL
                    var imgUrl = "";
                    if (item.goods_img) {
                        var firstImg = item.goods_img.split(';')[0].trim();
                        if (firstImg.indexOf('http') === 0) {
                            imgUrl = firstImg;
                        } else {
                            imgUrl = API_BASE_URL + firstImg;
                        }
                    } else {
                        imgUrl = "https://via.placeholder.com/300x300?text=No+Image";
                    }
                    
                    // 格式化价格
                    var discountPrice = parseFloat(item.discount || 0).toFixed(2);
                    var originalPrice = parseFloat(item.amount || 0).toFixed(2);
                    
                    // 构建价格HTML
                    var priceHtml = '<span class="price">￥' + discountPrice + '</span>';
                    // 如果有原价且原价大于现价，显示原价（带删除线）
                    if (originalPrice && parseFloat(originalPrice) > parseFloat(discountPrice)) {
                        priceHtml += ' <span style="color: #999;font-size: 0.22rem;text-decoration: line-through;margin-left: 4px;">￥' + originalPrice + '</span>';
                    }
                    
                    html += '<li class="span4">' +
                        '<div class="bui-pic goods-item" data-goods-id="' + item.id + '">' +
                        '<div class="bui-pic-img"><img src="' + imgUrl + '" alt="' + (item.goods_name || '商品') + '" onerror="this.src=\'https://via.placeholder.com/300x300?text=Error\'"></div>' +
                        '<div class="bui-pic-title">' + (item.goods_name || '商品名称') + '</div>' +
                        '<div class="price-section">' +
                        priceHtml +
                        '</div>' +
                        '</div>' +
                        '</li>';
                });
            } else {
                html = '<li style="width:100%;text-align:center;padding:20px;color:#999;">暂无商品</li>';
            }
            
            $("#goodsList").html(html);
            
            // 重新绑定商品点击事件
            setTimeout(function() {
                $(".goods-item").off("click").on("click", function() {
                    var goodsId = $(this).attr("data-goods-id");
                    if (goodsId) {
                        window.location.href = "./goodsInfo.html?id=" + goodsId;
                    }
                });
            }, 100);
            
            // 重新初始化按钮点击事件（如果bui库可用）
            if (typeof bui !== 'undefined' && typeof bui.btn === 'function') {
                try {
                    bui.btn({id:".bui-page",handle:".bui-pic"}).load();
                } catch(e) {
                    console.warn("bui.btn初始化失败:", e);
                }
            }
        }

        // 使用原生XMLHttpRequest获取商品列表（备用方案）
        function loadGoodsListNative() {
            console.log("使用原生XHR请求商品列表:", GOODS_LIST_API);
            
            var xhr = new XMLHttpRequest();
            xhr.open('POST', GOODS_LIST_API, true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.timeout = 10000;
            
            xhr.onload = function() {
                console.log("XHR请求完成，状态码:", xhr.status);
                if (xhr.status >= 200 && xhr.status < 300) {
                    try {
                        var response = JSON.parse(xhr.responseText);
                        console.log("XHR请求成功:", response);
                        if (response && response.code === 200 && response.data) {
                            renderGoods(response.data);
                        } else {
                            console.error("XHR获取商品列表失败:", response);
                            $("#goodsList").html('<li style="width:100%;text-align:center;padding:20px;color:#999;">加载失败，请稍后重试</li>');
                        }
                    } catch (e) {
                        console.error("XHR解析JSON失败:", e, xhr.responseText);
                        $("#goodsList").html('<li style="width:100%;text-align:center;padding:20px;color:#999;">数据解析失败</li>');
                    }
                } else {
                    console.error("XHR请求失败，状态码:", xhr.status);
                    $("#goodsList").html('<li style="width:100%;text-align:center;padding:20px;color:#999;">请求失败，错误码: ' + xhr.status + '</li>');
                }
            };
            
            xhr.onerror = function() {
                console.error("XHR请求出错");
                $("#goodsList").html('<li style="width:100%;text-align:center;padding:20px;color:#999;">网络错误，请检查网络连接</li>');
            };
            
            xhr.ontimeout = function() {
                console.error("XHR请求超时");
                $("#goodsList").html('<li style="width:100%;text-align:center;padding:20px;color:#999;">请求超时，请稍后重试</li>');
            };
            
            xhr.send();
        }

        // 获取商品列表
        function loadGoodsList() {
            console.log("开始请求商品列表:", GOODS_LIST_API);
            
            // 显示加载提示
            $("#goodsList").html('<li style="width:100%;text-align:center;padding:20px;color:#999;">正在加载商品...</li>');
            
            // 优先使用zepto的ajax，如果失败则使用原生XHR
            if (typeof $ !== 'undefined' && $.ajax) {
                console.log("使用zepto.ajax");
                $.ajax({
                    url: GOODS_LIST_API,
                    type: "POST",
                    dataType: "json",
                    crossDomain: true,
                    timeout: 10000,
                    beforeSend: function(xhr) {
                        console.log("发送请求前");
                    },
                    success: function(response) {
                        console.log("请求成功:", response);
                        if (response && response.code === 200 && response.data) {
                            console.log("商品数据:", response.data);
                            renderGoods(response.data);
                        } else {
                            console.error("获取商品列表失败:", response);
                            $("#goodsList").html('<li style="width:100%;text-align:center;padding:20px;color:#999;">加载失败，请稍后重试</li>');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("zepto.ajax请求失败，尝试使用原生XHR:", {
                            status: status,
                            error: error,
                            xhr: xhr,
                            readyState: xhr.readyState,
                            statusText: xhr.statusText,
                            responseText: xhr.responseText
                        });
                        
                        // 如果zepto ajax失败，尝试使用原生XHR
                        console.log("切换到原生XHR");
                        loadGoodsListNative();
                    }
                });
            } else {
                console.log("zepto.ajax不可用，直接使用原生XHR");
                loadGoodsListNative();
            }
        }

        // 页面初始化函数
        function initPage() {
            console.log("开始初始化页面");
            
            // 在线状态管理由 chat-status.js 自动处理，无需手动初始化
            
            // 检查DOM元素是否存在
            if ($("#goodsList").length === 0) {
                console.error("找不到商品列表容器 #goodsList");
                setTimeout(function() {
                    if ($("#goodsList").length > 0) {
                        console.log("延迟后找到容器，开始加载商品");
                        loadGoodsList();
                    } else {
                        console.error("仍然找不到商品列表容器");
                    }
                }, 500);
                return;
            }
            
            console.log("找到商品列表容器，开始加载商品");
            // 立即加载商品列表（不依赖bui库）
            loadGoodsList();
            
            // 初始化bui相关功能（如果bui库可用）
            if (typeof bui !== 'undefined') {
                console.log("bui库已加载，初始化bui功能");
                try {
                    bui.btn({id:".bui-page",handle:".bui-pic"}).load();
                } catch(e) {
                    console.warn("bui.btn初始化失败:", e);
                }
            } else {
                console.warn("bui库未加载，跳过bui相关功能");
            }
            
            // 绑定导航点击事件（使用原生方式，不依赖bui.load）
            $("#homeGo").on("click", function(e) {
                e.preventDefault();
                window.location.href = "./index.html";
            });
            $("#classifyGo").on("click", function(e) {
                e.preventDefault();
                window.location.href = "./clsssify.html";
            });
            $("#shopCartGo").on("click", function(e) {
                e.preventDefault();
                if (typeof bui !== 'undefined' && bui.load) {
                    bui.load({ url: "/index/index/shopCart"});
                } else {
                    window.location.href = "./shopCart.html";
                }
            });
            $("#orderQueryGo").on("click", function(e) {
                e.preventDefault();
                if (typeof bui !== 'undefined' && bui.load) {
                    bui.load({ url: "/index/index/orderQuery"});
                } else {
                    window.location.href = "./orderQuery.html";
                }
            });
        }

        // 优先使用zepto的ready
        if (typeof $ !== 'undefined') {
            $(document).ready(function() {
                console.log("DOM加载完成（zepto）");
                initPage();
            });
        }

        // 如果bui库可用，也监听bui.ready（作为额外保障）
        if (typeof bui !== 'undefined' && typeof bui.ready === 'function') {
            bui.ready(function() {
                console.log("bui.ready 执行");
                // 如果商品还没加载，再次尝试
                if ($("#goodsList").children().length === 0 || 
                    $("#goodsList").text().indexOf("正在加载") !== -1) {
                    console.log("bui.ready后再次检查商品加载状态");
                }
            });
        } else {
            console.warn("bui库未加载或bui.ready不可用");
        }
        
        // 使用window.onload作为最终备用方案
        window.addEventListener('load', function() {
            console.log("window.load 执行");
            setTimeout(function() {
                // 如果商品列表还是空的，强制加载
                if ($("#goodsList").length > 0) {
                    var childrenCount = $("#goodsList").children().length;
                    var text = $("#goodsList").text();
                    if (childrenCount === 0 || text.indexOf("正在加载") !== -1 || text.indexOf("暂无商品") !== -1) {
                        console.log("window.load后检查：商品未加载，强制加载");
                        loadGoodsList();
                    } else {
                        console.log("window.load后检查：商品已加载，无需重复加载");
                    }
                }
            }, 500);
        });
        
        // 页面关闭/隐藏时的离线通知由 chat-status.js 自动处理
    </script>
</body>
</html>
